﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Bigger.Framework;

namespace Bigger.Study.ConsoleApp.Async
{
    public class APMAsyncExample : IExample
    {
        public void Execute()
        {
            Func<string> objFunc = () =>
            {
                for (int i = 0; i < 10; i++)
                {
                    ConsoleHelper.WriteLineYellow("Func执行" + i);
                    Thread.Sleep(500);
                }
                return "委托返回结果";
            };

            Tuple<string, string> objTuple = new Tuple<string, string>("item1", "item2");

            //ConsoleHelper.WriteLineYellow("BeginInvoke代码行开始执行");
            //objFunc.BeginInvoke(FuncCallBack, objTuple);
            //ConsoleHelper.WriteLineYellow("BeginInvoke代码行结束执行");

            //IAsyncResult objAsyncResult = objFunc.BeginInvoke(FuncCallBack, objTuple);
            //while (true)
            //{
            //    if (objAsyncResult.IsCompleted)
            //    {
            //        ConsoleHelper.WriteLineYellow("Func异步执行完成");
            //        break;
            //    }
            //}

            //ConsoleHelper.WriteLineYellow("BeginInvoke代码行开始执行");
            //IAsyncResult objAsyncResult = objFunc.BeginInvoke(FuncCallBack, objTuple);
            //ConsoleHelper.WriteLineYellow("BeginInvoke代码行结束执行");
            //objAsyncResult.AsyncWaitHandle.WaitOne();

            ConsoleHelper.WriteLineYellow("BeginInvoke代码行开始执行");
            IAsyncResult objAsyncResult = objFunc.BeginInvoke(FuncCallBack, objTuple);
            ConsoleHelper.WriteLineYellow("BeginInvoke代码行结束执行");
            //objAsyncResult.AsyncWaitHandle.WaitOne();
            string result = objFunc.EndInvoke(objAsyncResult);
            ConsoleHelper.WriteLineYellow(result);
        }

        void FuncCallBack(IAsyncResult asyncResult)
        {
            Tuple<string, string> objTuple = asyncResult.AsyncState as Tuple<string, string>;
            ConsoleHelper.WriteLineYellow("回调执行，返回传入参数：" + objTuple.JsonSerialize());
        }
    }
}
